﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCS.Core.Models;
using System.Linq.Expressions;
using SCSService;
using SCS.Core.ViewModels;

namespace SCS.Core.Controllers
{
    public class HomeMasterController : BaseController
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {

            return RedirectToAction("BusinessStatistics");

        }
        #region Thống kê bán thẻ
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult BusinessStatistics(int? id, string ProductNameSearch, string ProductCodeSearch)
        {
            //Id đầu vào là typeId
            int currentPage = 1;
            int pageSize = 20000;
            string sortField = "ProductID";
            string sortDirection = "Asc";

            int siteGuid = GetSiteGuid();


            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return BusinessStatistics(ProductNameSearch, ProductCodeSearch, currentPage, pageSize, sortField, sortDirection, null, id, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult BusinessStatistics(string ProductNameSearch, string ProductCodeSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là typeId
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 20000;
            }

            if (siteGuid == null)
            {

                siteGuid = GetSiteGuid();

            }

            ViewData["currentPage"] = currentPage;


            var query = Models.StockModel.GetListProductByTypeProduct(ProductNameSearch, ProductCodeSearch, id, LanguageID, (int)siteGuid).AsQueryable();
            ViewData["ListProduct"] = query;
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Product), "product");
                var sortExpression = Expression.Lambda<Func<Product, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Product>();


            // Set up our ViewModel
            var viewModel = new ListProductViewModels
            {
                ProductItem = result,
                TypeProduct = id != null ? Models.StockModel.GetTypeProduct((int)id) : null,
                ProductNameSearch = ProductNameSearch,
                ProductCodeSearch = ProductCodeSearch
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }
        #endregion

        #region List Oreder
        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.OrderViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.OrderViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListOrder(string FullNameSearch, int? StatusSearch, DateTime? StartDate, DateTime? EndDate, string PhoneSearch, string EmailSearch)
        {
            int currentPage = 1;
            int pageSize = 20000;
            string sortField = "OrderID";
            string sortDirection = "Asc";

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListOrder(FullNameSearch, StatusSearch, StartDate, EndDate, PhoneSearch, EmailSearch, currentPage, pageSize, sortField, sortDirection, null, siteGuid);


        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListOrder(string FullNameSearch, int? StatusSearch, DateTime? StartDate, DateTime? EndDate, string PhoneSearch, string EmailSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 20000;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;
            var query = HomeMasterModel.GetListOrder(StatusSearch, StartDate, EndDate, (int)siteGuid).AsQueryable();
            DateTime date = new DateTime();
            if (EndDate != null)
            {
                 date = (DateTime)EndDate;
                 date=date.AddDays(1);
                 query = HomeMasterModel.GetListOrder(StatusSearch, StartDate, date, (int)siteGuid).AsQueryable();
            }
           
           
            int totalRows = query.Count();
            if (StatusSearch>=0)
            {
            query = query.Where(m => m.OrderStatus == StatusSearch);
            }

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Customer_Order), "Customer_Order");
                var sortExpression = Expression.Lambda<Func<Customer_Order, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Customer_Order>();

            // Set up our ViewModel
            var viewModel = new OrderViewModels
            {
                ListCustomer_Order = result,
                StartDate = StartDate,
                StatusSearch = StatusSearch,
                EndDate = EndDate
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }
        #endregion


        #region Customer order detail

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.DetailOrderViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.DetailOrderViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult DetailOrder(int id, string FullNameSearch, int? StatusSearch, DateTime? StartDate, DateTime? EndDate, string PhoneSearch, string EmailSearch)
        {
            int currentPage = 1;
            int pageSize = 20;
            string sortField = "OrderID";
            string sortDirection = "Asc";

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return DetailOrder(id, FullNameSearch, StatusSearch, StartDate, EndDate, PhoneSearch, EmailSearch, currentPage, pageSize, sortField, sortDirection, null, siteGuid);


        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult DetailOrder(int id, string FullNameSearch, int? StatusSearch, DateTime? StartDate, DateTime? EndDate, string PhoneSearch, string EmailSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid)
        {

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 20;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;

            var query = HomeMasterModel.GetListDetail(id).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Detail_Order), "Detail_Order");
                var sortExpression = Expression.Lambda<Func<Detail_Order, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Detail_Order>();

            // Set up our ViewModel
            var viewModel = new DetailOrderViewModels
            {
                lstDetailOrder = result

            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }


        public ActionResult DeleteCustomerOrder(int id, string returnUrl)
        {
            var query = HomeMasterModel.GetListDetail(id).AsQueryable();
            byte StatusInvoice = 0;         //Trang thái hóa đơn chưa xác nhận
            byte StatusCustomrOrder = 0;    //Trạng thái chưa thanh toán xóa để tái sử dụng code, serial
            var getDistinctStatus = (from c in query
                                         select c.StatusOrder).Distinct();
            if (StatusCustomrOrder == getDistinctStatus.First())
            {

                foreach (var item in query)
                {
                    if (HomeMasterModel.checkedProduct_Stock_Detail(item.ProductStockDetailID) > 0)
                    {
                        //Update status=1 of Product_Stock_Detail
                        HomeMasterModel.UpdateStatusProduct_Stock_Detail(item.ProductStockDetailID, 1);
                        HomeMasterModel.DeleteOrder_Item_Detail(item.OrderItemDetailID);
                    }
                    else
                    {
                        ViewData["Result"] = "Delete Customer Order have product. You can't delete";
                    }
                }
                foreach (var item in query)
                {
                    try
                    {
                        HomeMasterModel.DeleteOrderItems(item.OrderItemID);
                    }
                    catch
                    {
                        ViewData["Result"] = "Delete Customer Order have product. You can't delete";
                    }

                }
                //Chỉ được xóa những trạng thái hóa đơn status=0;
                try
                {
                    HomeMasterModel.DeleteInvoice(id, StatusInvoice);
                    HomeMasterModel.DeleteCustomerOrder(id);
                }
                catch {
                    ViewData["Result"] = "Delete Invoice have Statu. You can't delete";
                }
            }
            else
            {
                ViewData["Result"] = "Delete Customer Order .You can't delete !  ";
            }
            return Redirect(returnUrl);
        }

        #endregion
        #region Popup Shipment
        public JsonResult GetListPupupShipment(int? id)
        {
            
            var lShipment = HomeMasterModel.GetShipmentByOrderID(id??0);
            var result = "";
            var LinkString = "";
            var LinkDetailOrder="";
            LinkDetailOrder = "/" + DefaultSiteGuidGetter().ToString() + "/" + DefaultLanguageGetter() + "/HomeMaster/DetailOrder/" + id.ToString();
            LinkString = "<a href=" + LinkDetailOrder + " style='color: red;text-decoration: underline;float: right;' >Danh sách chi tiết</a>";
            
            if (lShipment != null)
            {
                result +="Tên người nhân: "+ lShipment.FullName;
                result += "<br/> Địa chỉ :" + lShipment.Address.ToString();
                result += "<br/> Thuộc thành phố :" + lShipment.City;
                result += "<br/> Ngày chuyền hàng: " + lShipment.CreateDate.ToString();
                result += "<br/> Địa chỉ Email" + lShipment.Email.ToString();
                result += "<br/> " + LinkString;
                
            }
           
            //List<Shipment> lShipment = HomeMasterModel.GetListShipment(id).ToList();
            return Json(result);

        }
        public ActionResult ChangeStatusShipment(int id, int? proid)
        {
            
            int OrderID = HomeMasterModel.GetOrder_ItemByID(id).OrderID??0;
            Shipment  GetShipment = HomeMasterModel.GetShipmentByOrderID(OrderID);
            Shipment_Item SetShipment = new Shipment_Item();

            SetShipment.ShipmentID = GetShipment.ShipmentID;
            SetShipment.OrderItemID=id;
            if (proid == 1)
            {
                HomeMasterModel.InsertShipment_Item(SetShipment);
            }
            else {
                HomeMasterModel.DeleteShipment_Item(GetShipment.ShipmentID, id);
            }
            
            string outStr = "" + proid;
            return Json(outStr);
        }
        #endregion

    }
}
